<?php
/*
 module:		红娘管理
 create_time:	2022-03-24 10:01:45
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\ZhCollection as ZhCollectionModel;
use app\api\model\ZhMatchmakerAddinfo;
use app\api\model\ZhMatchmakerIntroduce;
use app\api\model\ZhMatchmakerLevel;
use app\api\model\ZhWechatMediaLog;
use app\api\service\ZhMatchmakerService;
use app\api\model\ZhMatchmaker as ZhMatchmakerModel;
use app\backend\controller\ZhVipIntroduce;
use org\Category;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use think\response\Json;
use wechat\MediaCheckAsync;
use wechat\MsgSecCheck;

class ZhMatchmaker extends Common
{
    function getLevelList(){
        $res = \app\backend\model\ZhMatchmakerLevel::where(['status' => 1])->order(['createtime' => 'desc'])->select();
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    function test(){
        $wxapp_id = 3;
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        $user = MemberModel::find(506);
        /*
        $data = ['name' => '紫龙'];

        try {
            $this->wechatTextCheck($data, $wxSetting, $user['openid']);
            echo "ok";
        }catch (\Exception $e){
            print_r($e->getMessage());
        }*/
        $data = ['pictures' => json_encode(['http://yuncc.xizihongniang.cn/api/202405/202405241137270102326.jpg'])];
        $uId = 506;
        $matchmaker = [];
        $traceIds = $this->wechatPicCheck($data, $matchmaker, $wxSetting,  $uId, $user['openid']);
        print_r($traceIds);
        $matchmakerId = 145;
        if(! empty($matchmakerId)) {
            ZhWechatMediaLog::whereIn('trace_id', $traceIds)->update(['matchmaker_id' => $matchmakerId]);
        }
        exit;
    }

    /**
     * @api             {post} /ZhMatchmaker/add 01、添加
     * @apiGroup        ZhMatchmaker
     * @apiVersion      1.0.0
     * @apiDescription  添加
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {string}            name 姓名 (必填)
     * @apiParam (输入参数：) {string}            phone 电话 (必填)
     * @apiParam (输入参数：) {string}            id_number 身份证号 (必填)
     * @apiParam (输入参数：) {string}            wechat_number 微信号 (必填)
     * @apiParam (输入参数：) {string}            city 市区 (必填)
     * @apiParam (输入参数：) {string}            address 详细地址 (必填)
     * @apiParam (输入参数：) {int}                is_personal 是否个人 个人|1|success,机构|0|warning
     * @apiParam (输入参数：) {string}            organization_name 机构名称
     * @apiParam (输入参数：) {string}            credit_code 公司信用代码
     * @apiParam (输入参数：) {string}            remarks 简介
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function add()
    {
        $matchmakerId = $this->request->post('matchmaker_id');
        $wxapp_id     = $this->request->post('wxapp_id');
        $op     = $this->request->post('op');
        $uId     = $this->request->post('uid');
      //  $uId          = $this->request->uid;
        if($op=="test"){
            $uId=380;
        }
        
        if (!$wxapp_id) {
            $wxapp_id=3;
           // return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();

        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        if($this->request->has("head_portrait")){
            $data["head_portrait"]=$this->request->post("head_portrait");
        }
        if($this->request->has("city")){
            $data["city"]=$this->request->post("city");
        }
        if($this->request->has("county")){
            $data["county"]=$this->request->post("county");
        }
        if($this->request->has("province")){
            $data["province"]=$this->request->post("province");
        }
        if($this->request->has("send_word_video")){
            $data["send_word_video"]=$this->request->post("send_word_video");
        }
        if($this->request->has("summarize_txt")){
            $data["summarize_txt"]=$this->request->post("summarize_txt");
        }
        if($this->request->has("summarize_videos")){
            $data["summarize_videos"]=$this->request->post("summarize_videos");
        }
        if($this->request->has("share_videos")){
            $data["share_videos"]=$this->request->post("share_videos");
        }
        if($this->request->has("hand_success_videos")){
            $data["hand_success_videos"]=$this->request->post("hand_success_videos");
        }
        if($this->request->has("name")){
            $data["name"]=$this->request->post("name");
        }
        if($this->request->has("age")){
            $data["age"]=$this->request->post("age");
        }
        if($this->request->has("phone")){
            $data["phone"]=$this->request->post("phone");
        }
        if($this->request->has("id_number")){
            $data["id_number"]=$this->request->post("id_number");
        }
        if($this->request->post("boy_desc")){
            $data["boy_desc"]=$this->request->post("boy_desc");
        }
        if($this->request->post("expiretime")){
            $tmpExireTime =$this->request->post("expiretime");
            if(is_numeric($tmpExireTime)){
                $data["expiretime"] = $tmpExireTime;
            }else{
                $data["expiretime"] = strtotime($tmpExireTime);
            }
        }
        if($this->request->post("girl_desc")){
            $data["girl_desc"]=$this->request->post("girl_desc");
        }
        if($this->request->post("hand_success_desc")){
            $data["hand_success_desc"]=$this->request->post("hand_success_desc");
        }
        if($this->request->post("hand_success_num")){
            $data["hand_success_num"]=$this->request->post("hand_success_num");
        }
        if($this->request->post("hand_success_picture")){
            $data["hand_success_picture"]=$this->request->post("hand_success_picture");
        }
        if($this->request->post("wechat_number")){
            $data["wechat_number"]=$this->request->post("wechat_number");
        }
        if($this->request->post("city")){
            $data["city"]=$this->request->post("city");
        }
        if($this->request->post("address")){
            $data["address"]=$this->request->post("address");
        }
        if($this->request->post("is_personal")){
            $data["is_personal"]=$this->request->post("is_personal");
        }
        if($this->request->post("organization_name")){
            $data["organization_name"]=$this->request->post("organization_name");
        }
        if($this->request->post("credit_code")){
            $data["credit_code"]=$this->request->post("credit_code");
        }
        if($this->request->post("remarks")){
            $data["remarks"]=$this->request->post("remarks");
        }
        if($this->request->post("logo")){
            $data["logo"]=$this->request->post("logo");
        }
        if($this->request->post("work_years")){
            $data["work_years"]=$this->request->post("work_years");
        }
        if($this->request->post("lower_matchmaker_num")){
            $data["lower_matchmaker_num"]=$this->request->post("lower_matchmaker_num");
        }
        if($this->request->post("pictures")){
            $data["pictures"]=$this->request->post("pictures");
        }
        if($this->request->post("is_collection")){
            $data["is_collection"]=$this->request->post("is_collection");
        }
        if($this->request->post("level_id")){
            $data["level_id"]=$this->request->post("level_id");
        }
        if($this->request->post("videos")){
            $data["videos"]=$this->request->post("videos");
        }
        if($this->request->post("send_word")){
            $data["send_word"]=$this->request->post("send_word");
        }
        if($this->request->post("service_zone")){
            $data["service_zone"]=$this->request->post("service_zone");
        }
        if($this->request->post("sex")){
            $data["sex"]=$this->request->post("sex");
        }
        if($this->request->post("is_personal")){
            $data["is_personal"]=$this->request->post("is_personal");
        }

        $data["send_word_video"]=json_encode($data["send_word_video"]);
        $data["summarize_videos"]=json_encode($data["summarize_videos"]);
        $data["share_videos"]=json_encode($data["share_videos"]);
         $data["hand_success_videos"]=json_encode($data["hand_success_videos"]);
        $data["hand_success_picture"]=json_encode($data["hand_success_picture"]);
        $data["videos"]=json_encode($data["videos"]);
        $data["pictures"]=json_encode($data["pictures"]);


        if ($data['is_personal'] == 1) {
            $data['organization_name'] = '';
            $data['credit_code']       = '';
//            $data['remarks']           = '';
        }
        $data['status']=0;
  /*      //微信文本安全校验
        try{
            $this->wechatTextCheck($data, $wxSetting, $user['openid']);
        } catch (\Exception $e) {
            return $this->ajaxReturn($this->errorCode, '您提交的信息涉及违规，请修改！');
        }*/
        //查询红娘信息
        $matchmaker = ZhMatchmakerModel::where("u_id", $uId)->find();
        if(empty($matchmaker)){
            $matchmaker = [];
        }else{
            $matchmaker = $matchmaker->toArray();
        }
        //红娘名片信息
          if($this->request->has("mp_name")){
            $data["mp_name"]=$this->request->post("mp_name");
        }
          if($this->request->has("mp_tel")){
            $data["mp_tel"]=$this->request->post("mp_tel");
        }
         if($this->request->has("mp_province")){
            $data["mp_province"]=$this->request->post("mp_province");
        }
         if($this->request->has("mp_city")){
            $data["mp_city"]=$this->request->post("mp_city");
        }
         if($this->request->has("mp_address")){
            $data["mp_address"]=$this->request->post("mp_address");
        }

        //微信图片安全校验
        $traceIds = $this->wechatPicCheck($data, $matchmaker, $wxSetting,  $uId, $user['openid']);
        if ($matchmakerId) {
            $where = [
                'matchmaker_id' => $matchmakerId,
                'wxapp_id'      => $wxapp_id,
                //'u_id'          => $uId
            ];
            $res   = ZhMatchmakerModel::where($where)->update($data);
            /*if($op=="test"){
                 print_r($data);
                 print_R(ZhMatchmakerModel::getLastsql());exit();
                 exit();
            }*/

            $m_res=\app\api\model\Member::where(["uid"=>$uId])->update(["matchmaker_id"=>$matchmakerId]);
           // print_R(ZhMatchmakerModel::getLastsql());exit(); 
        } else {
            $data['wxapp_id'] = $wxapp_id;
            $data['u_id']     = $uId;
            if(! isset($data['hand_success_num'])){
                $data['hand_success_num'] = 0;
            }
            if(! isset($data['hand_success_desc'])){
                $data['hand_success_desc'] = "";
            }
            if(! isset($data['top_matchmaker_id'])){
                $data['top_matchmaker_id'] = 0;
            }
            if(! isset($data['boy_desc'])){
                $data['boy_desc'] = '';
            }
            if(! isset($data['girl_desc'])){
                $data['girl_desc'] = '';
            }
           // $res              = ZhMatchmakerModel::where(['wxapp_id' => $wxapp_id, 'u_id' => $uId])->find();
            $res = ZhMatchmakerService::add($data);
            $matchmakerId = $res;
            if ($res) {
                //为了让用户点击红娘协议，在这里更新用户表关联红娘的ID
                $m_res=\app\api\model\Member::where(["uid"=>$uId])->update(["matchmaker_id"=>$res]);
                // 修改是否是红娘字段, 一个用户可以两个身份，所以不改身份
//                MemberModel::where([
//                    'wxapp_id' => $wxapp_id,
//                    'uid'      => $uId
//                ])->update([
//                    'is_matchmaker' => 1
//                ]);
            } else {
                return $this->ajaxReturn($this->errorCode, '操作失败');
            }
        }
        //有微信审核记录，根据微信返回的trace_id更新资料ID
        if(! empty($traceIds)){
            ZhWechatMediaLog::whereIn('trace_id', $traceIds)->update(['matchmaker_id' => $matchmakerId]);
        }
        return $this->ajaxReturn($this->successCode, '操作成功', $res);
    }

    //微信文本校验
    private function wechatTextCheck($data, $wxSetting, $openid) {
        $checkContent = "";
        //send_word 详细资料（红娘寄语）
      //  $fields = ['real_name','name','send_word','boy_desc','girl_desc','summarize_txt'];
        //改成只检测昵称一个字段
        $fields = ['name'];
        foreach ($fields as $f){
            if(isset($data[$f])){
                $v = trim($data[$f]);
                if($v != ""){
                    if($checkContent != ""){
                        $checkContent .= ",";
                    }
                    $checkContent .= $v;
                }
            }
        }
        if(! empty($checkContent)) {
            //有问题，抛出异常，外层补捕
            MsgSecCheck::checkText($wxSetting['app_id'], $wxSetting['app_secret'], $openid, $checkContent);
        }
    }

    //微信图片审核, 返回traceId 数组

    /**
     * @author lichunguang
     * @since 2024/5/24 12:04
     * @param $data array 提交的数据
     * @param $dbData array 数据库中的数据
     * @param $wxSetting array 微信配置
     * @param $uId int 红娘的uid
     * @param $openid string 红娘的openid
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    private function wechatPicCheck($data, $dbData, $wxSetting, $uId, $openid){
        $traceIds = [];
        $newPhotos = [];
        $headPortrait = trim($data['head_portrait'] ?? '');
        if(! empty($headPortrait)){
            $newPhotos[] = $headPortrait;
        }
        $logo = trim($data['logo'] ?? '');
        if(! empty(trim($logo))){
            $newPhotos[] = trim($logo);
        }
        $photos = $data['pictures'] ?? "";
        if(! empty($photos)){
            $newPhotos = array_merge($newPhotos, json_decode($photos, true));
        }
        
        if(! empty($dbData)){//已有资料，已添加的图片，不用重新发起审核
            $existPhotos = [];
            if(trim($dbData['head_portrait']) != ""){
                $existPhotos[] = trim($dbData['head_portrait']);
            }
            if(trim($dbData['pictures']) != ""){
                $tmpPhotos = json_decode(trim($dbData['pictures']), true);
                $existPhotos = array_merge($existPhotos, $tmpPhotos);
            }
            $newPhotos = array_values(array_diff($newPhotos, $existPhotos));
            $existPhotos = null;
        }
        //如果有未审核的照片
        if(! empty($newPhotos)){
            foreach($newPhotos as $photo){//没有资料，新增
                //这里只提交，不抛异常
                $traceIds[] = MediaCheckAsync::checkMedia($wxSetting['app_id'], $wxSetting['app_secret'], $uId, $openid, 2, $photo);
            }
        }
        return $traceIds;
    }


    /**
     * @api             {get} /ZhMatchmaker/view 02、查看详情
     * @apiGroup        ZhMatchmaker
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            matchmaker_id 主键ID
     * @apiParam (输入参数：) {string}            800px 主键ID
     * @apiParam (输入参数：) {string}            100% 主键ID
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      =  $this->request->get('uid');
        $op      =  $this->request->get('op');
        $phone= $this->request->get('phone');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if($op=="test"){
            $uId=378;
        }
        if(intval($uId)>0){
            $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户 uid:'.$uId." phone:".$phone);
            }
            $data  = [
                'wxapp_id' => $wxapp_id,
                'u_id'     => $uId,
            ];
        }else{
            $data  = [
                'wxapp_id' => $wxapp_id,
                'phone'     => $phone,
            ];
        }
        $field = '*';
        $res   = ZhMatchmakerModel::where($data)->find();
        if ($res) {
            $res['createtime'] = date('Y-m-d H:i:s', $res['createtime']);
            $res['logo']       = $res['logo'] ? $res['logo'] : '';
            $res['pictures']             = htmlspecialchars_decode($res['pictures']);
            $res['videos']               = htmlspecialchars_decode($res['videos']);
            $res['share_videos']               = htmlspecialchars_decode($res['share_videos']);
            $res['hand_success_videos']               = htmlspecialchars_decode($res['hand_success_videos']);
            $res['hand_success_picture'] = htmlspecialchars_decode($res['hand_success_picture']);
            $res['summarize_videos']=htmlspecialchars_decode( $data['summarize_videos']);

            if(intval($res['nature'])==1){
                $res['nature']="个人";
            }elseif(intval($res['nature'])==2){
                $res['nature']="机构";
            }else{
                $res['nature']="其他";
            }

        } else {
            $res = [];
        }

        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    /**
     * @api             {get} /ZhMatchmaker/index 03、首页数据列表
     * @apiGroup        ZhMatchmaker
     * @apiVersion      1.0.0
     * @apiDescription  首页数据列表
     * @apiParam (输入参数：) {int}            [limit] 每页数据条数（默认20）
     * @apiParam (输入参数：) {int}            [page] 当前页码
     * @apiParam (输入参数：) {string}        [name] 姓名
     * @apiParam (输入参数：) {string}        [city] 市区
     * @apiParam (输入参数：) {int}            [is_personal] 是否个人 个人|1|success,机构|0|warning
     * @apiParam (输入参数：) {string}        [organization_name] 机构名称
     * @apiParam (输入参数：) {string}        [createtime_start] 创建时间开始
     * @apiParam (输入参数：) {string}        [createtime_end] 创建时间结束
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据
     * @apiParam (成功返回参数：) {string}        array.data.list 返回数据列表
     * @apiParam (成功返回参数：) {string}        array.data.count 返回数据总数
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"查询失败"}
     */
    function index()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $limit     = $this->request->get('limit', 4, 'intval');
        $page      = $this->request->get('page', 1, 'intval');
        $show_home = $this->request->get('show_home', 0, 'intval');

        //关键词搜索
        $keyword=$this->request->get('keyword', '');
        $age=$this->request->get('age', '');
        $sex=$this->request->get('sex', '');
        $service_zone=$this->request->get('service_zone', '');
        $level_id=$this->request->get('level_id', '');
        $work_years=$this->request->get('work_years', '');
        $where             = [];
        $where2="";
        $where[] = ["wxapp_id","=",$wxapp_id];
        $where[] = ["status","=",1];

     /*   if ($age) {
            $where[] = ['age', '=', $age];

        }*/
        if ($age && $age == '50后') {
            $where[] = ['age', 'between', [65, 74]];
        }

        if ($age && $age == '60后') {
            $where[] = ['age', 'between', [55, 64]];
        }

        if ($age && $age == '70后') {
            $where[] = ['age', 'between', [45, 54]];
        }
        if ($age && $age == '80后') {
            $where[] = ['age', 'between', [35, 44]];
        }
        if ($age && $age == '90后') {
            $where[] = ['age', 'between', [25, 34]];
        }
        if ($age && $age == '00后') {
            $where[] = ['age', '<', 25];
        }


        if ($sex) {
            $where[] = ['sex', '=', $sex];
        }
        if ($level_id) {
            $where[] = ['level_id', '=', $level_id];
        }
        if ($work_years) {
            $where[] = ['work_years', '=', $work_years];
        }
        if($service_zone > 0){
            $where[] = ['service_zone', 'like',  '%' . $service_zone . '%'];
        }

        // 年龄（年龄区间25-75）、性别、服务区域、红娘等级、红娘经验（年限区间1-30）
        if($keyword){
            $where2=" status=1  ";
            $where2 .= " and ( name like '%{$keyword}%' or  phone like '%{$keyword}%'
                        or id_number like '%{$keyword}%' or  wechat_number like '%{$keyword}%'
                        or city like  '%$keyword%'  or address like '%{$keyword}%'
                        or organization_name like '%{$keyword}%' or credit_code  like '%{$keyword}%'  
                        or remarks  like '%{$keyword}%' or age  like '%{$keyword}%'
                        or province like '%{$keyword}%'  or county like '%{$keyword}%' 
                        or hand_success_num  like '%{$keyword} %' or   service_zone like '%{$keyword}%'
                        or  hand_success_desc like '%{$keyword} %' or send_word  like '%{$keyword} %'  
                        or work_years like '%{$keyword}%' or boy_desc  like  '%{$keyword} %'  
                        or girl_desc  like '%{$keyword}%' or summarize_txt  like '%{$keyword}%'  
                         ) 
                        ";
        }
        if ($show_home == 1) {
            $where[] = ["show_home","=",1];
        }
        $field   = 'matchmaker_id,work_years,level_id,phone,name,lower_matchmaker_num,u_id,matchmaker_id,work_years,hand_success_num,id_number,city,wechat_number,organization_name,remarks,province,county,age';
        $orderby = 'matchmaker_id desc';
        if(trim($keyword)){
            $res = ZhMatchmakerService::indexList($where2, $field, $orderby, $limit, $page);
        }else{
            $res = ZhMatchmakerService::indexList($where, $field, $orderby, $limit, $page);
        }
        foreach ($res['list'] as &$v) {
            if ($v['u_id'] != 0) {
                $avatar      = MemberModel::where(['uid' => $v['u_id'], 'wxapp_id' => $wxapp_id])->value('avatar');
                $nickname     = MemberModel::where(['uid' => $v['u_id'], 'wxapp_id' => $wxapp_id])->value('nickname');
                $v['avatar'] = $avatar;
                $v['nickname'] = $nickname;
            } else {
                $v['avatar'] = '';
                $v['nickname'] = '';
            }
        }
        unset($v);
        return $this->ajaxReturn($this->successCode, '返回成功', htmlOutList($res));
    }


    /**
     * @api             {get} /ZhMatchmaker/detail 02、首页查看详情及旗下所有人员
     * @apiGroup        ZhMatchmaker
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            matchmaker_id 主键ID
     * @apiParam (输入参数：) {string}            800px 主键ID
     * @apiParam (输入参数：) {string}            100% 主键ID
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function detail()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $userId   = $this->request->get('user_id', '', 'serach_in');

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if ($userId) {
            $data = [
                'u_id'     => $userId,
                'wxapp_id' => $wxapp_id,
            ];
        } else {
            return $this->ajaxReturn($this->errorCode, '缺少信息参数');
        }

        // 获取用户id 用以判断用户是否登录
        $token = $this->request->header('Authorization');
        $uid   = 0;
        if ($token) {
            $jwt = Jwt::getInstance();
            $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                ->setSecrect(config('my.jwt_secrect'))
                ->setToken($token);
            $uid  = $jwt->decode()->getClaim('uid');
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户');
            }
        }

        $field          = 'name,sex,is_personal,organization_name,wxapp_id,logo,u_id,matchmaker_id,work_years,hand_success_num,lower_matchmaker_num,hand_success_picture,pictures,videos,remarks,boy_desc,girl_desc,service_zone,age,province,county,send_word,level_id,expiretime,hand_success_desc';
        $matchmakerInfo = ZhMatchmakerModel::where($data)->find();
        $nickname     = MemberModel::where(['uid' => $userId, 'wxapp_id' => $wxapp_id])->value('nickname');
        $matchmakerInfo['nickname'] = $nickname;

        if (empty($matchmakerInfo)) {
            return $this->ajaxReturn($this->errorCode, '红娘不存在');
        }

        //查会员表，获取实名状态
        $memberData             = MemberModel::where(['uid' => $matchmakerInfo['u_id'], 'wxapp_id' => $wxapp_id])->find();
        if ($matchmakerInfo['is_personal'] == 1) {
//            $matchmakerInfo['sex']  = $memberData['sex'];
            $matchmakerInfo['logo'] = $memberData['avatar'];
        } else {
//            $matchmakerInfo['logo'] = $this->request->domain() . $matchmakerInfo['logo'];
        }
        $matchmakerInfo['is_auth'] = $memberData['is_auth']; //实名状态，1已认证 0未认证
        $matchmakerInfo['hand_success_picture'] = $matchmakerInfo['hand_success_picture'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['hand_success_picture']), true) : [];
        $matchmakerInfo['pictures']             = $matchmakerInfo['pictures'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['pictures']), true) : [];
        $matchmakerInfo['videos']               = $matchmakerInfo['videos'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['videos']), true) : [];
        $matchmakerInfo['expiretime']           = date('Y-m-d H:i:s', $matchmakerInfo['expiretime']);
        $matchmakerInfo['share_videos']               = $matchmakerInfo['share_videos'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['share_videos']), true) : [];
        $matchmakerInfo['hand_success_videos']               = $matchmakerInfo['hand_success_videos'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['hand_success_videos']), true) : [];
        $matchmakerInfo['summarize_videos']               = $matchmakerInfo['summarize_videos'] ? json_decode(htmlspecialchars_decode($matchmakerInfo['summarize_videos']), true) : [];

        // 查询红娘等级
        if ($matchmakerInfo['level_id']) {
            $matchmakerInfo['level_name'] = ZhMatchmakerLevel::where(['id' => $matchmakerInfo['level_id']])->value('name');
        } else {
            $matchmakerInfo['level_name'] = '';
        }

        // 查看是否收藏
        $ZhCollectionData = ZhCollectionModel::where(['u_id' => $uid, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => 0])->find();
        if ($ZhCollectionData) {
            $matchmakerInfo['is_collection'] = $ZhCollectionData['status'];
        } else {
            $matchmakerInfo['is_collection'] = 0;
        }

        $res['matchmaker_info'] = $matchmakerInfo;
        //旗下人员
        $matchmakerUId = ZhMatchmakerModel::where(['matchmaker_id' => $matchmakerInfo['matchmaker_id'], 'wxapp_id' => $wxapp_id])->value('u_id');
        if (!$matchmakerUId) {
            return $this->ajaxReturn($this->errorCode, '红娘不存在');
        }
        $uidData         = MemberModel::where(['wxapp_id' => $wxapp_id, 'matchmaker_id' => $matchmakerUId])->count('uid');
        $res['qixiaNum'] = $uidData;
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }


    /**
     * {get} /ZhMatchmaker/viewByMatchmakerId 查询红娘信息
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function viewByMatchmakerId()
    {
        $wxapp_id     = $this->request->get('wxapp_id');
        $matchmakerId = $this->request->get('matchmaker_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $data  = [
            'wxapp_id'      => $wxapp_id,
            'matchmaker_id' => $matchmakerId,
        ];
        $field = '*';
        $res   = ZhMatchmakerModel::field($field)->where($data)->find();
        if ($res) {
            $res['createtime'] = date('Y-m-d H:i:s', $res['createtime']);
            $res['logo']       = $res['logo'] ? $res['logo'] : '';
        } else {
            $res = [];
        }

        if ($res['u_id']) {
            $res['member'] = MemberModel::where(['uid' => $res['u_id'], 'wxapp_id' => $wxapp_id])->field('phone,openid,nickname,avatar,real_name,sex')->find();
        }

        if ($res['pictures']) {
            $res['pictures'] = json_decode(htmlspecialchars_decode($res['pictures']), true);
        } else {
            $res['pictures'] = [];
        }

        if ($res['videos']) {
            $res['videos'] = json_decode(htmlspecialchars_decode($res['videos']), true);
        } else {
            $res['videos'] = [];
        }

        if ($res['hand_success_picture']) {
            $res['hand_success_picture'] = json_decode(htmlspecialchars_decode($res['hand_success_picture']), true);
        } else {
            $res['hand_success_picture'] = [];
        }

        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    public function introduce()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $data  = ZhMatchmakerIntroduce::where('id', 1)->find();
        $video = json_decode(htmlspecialchars_decode($data['video']), true);


        return $this->ajaxReturn($this->successCode, '返回成功', [
            'text'  => $data['text'],
            'video' => empty($video) ? '' : $video[0],
        ]);
    }

    public function vip_introduce()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $data  = ZhVipIntroduce::where('id', 1)->find();
        $video = json_decode(htmlspecialchars_decode($data['video']), true);

        return $this->ajaxReturn($this->successCode, '返回成功', [
            'text'  => $data['text'],
            'video' => empty($video) ? '' : $video[0],
        ]);
    }

    public function add_info(){
        $wxapp_id     = $this->request->post('wxapp_id');
        $postField = 'matchmaker_id,photos,content';
        $data      = $this->request->only(explode(',', $postField), 'post', null);
        $data["photos"]=json_encode( $data["photos"]);
        $data['createtime']=time();
        $data['wxapp_id']=$wxapp_id;
        $data['status']=0;
        $res=ZhMatchmakerAddinfo::create($data);
        return $this->ajaxReturn($this->successCode, '操作成功', $res);
    }

}

